#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
void Usage(char *arg)
{
    std::cout << "Usage:  please enter:" << std::endl;
    std::cout << arg << ' ' << "server ip " << "server port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //创建socket套接字
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0)
    {
        std::cerr << "socket error" << std::endl;
    }
    struct sockaddr_in server;
    //填充服务器信息，因为要给服务器发消息
    memset(&server, 0, sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());

    std::string message;
    while(true)
    {
        std::cout<<"Please Enter# ";
        std::getline(std::cin,message);
        sendto(socketfd,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));//给服务器发消息
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        char buffer[1024];
        ssize_t n=recvfrom(socketfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);//接收来自服务器的消息
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<"server echo# "<<buffer<<std::endl;
        }
    }

    return 0;
}